package com.joshua.spring.gateway.filter.response;

import com.joshua.spring.gateway.constant.SwaggerConstants;
import com.joshua.spring.gateway.constant.SymbolConstants;
import com.joshua.spring.gateway.properties.SwaggerIgnoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON;

/**
 * projectName dragon-cloud
 * package com.joshua.spring.gateway.filter.response
 * classname  GlobalResponseFilter
 * <p>
 * description 全局响应信息拦截器
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/7/13 15:10
 */
@Slf4j
@Component
public class GlobalResponseFilter implements GlobalFilter, Ordered {
    @Autowired
    private SwaggerIgnoreProperties swaggerIgnoreProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        ServerHttpResponse originalResponse = exchange.getResponse();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (APPLICATION_JSON.isCompatibleWith(getDelegate().getHeaders().getContentType())) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {
                        // probably should reuse buffers
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        String s = new String(content, StandardCharsets.UTF_8);
                        byte[] uppedContent;
                        if (path.contains(SwaggerConstants.DOCS_URI_WITH_PREFIX)) {
                            List<String> replaceStrings = swaggerIgnoreProperties.getReplaceStrings();
                            for (int i = 0; i < replaceStrings.size(); i++) {
                                s = s.replaceAll(replaceStrings.get(i), SymbolConstants.EMPTY_STR);
                            }
                            uppedContent = s.getBytes(StandardCharsets.UTF_8);
                        } else {
                            uppedContent = content;
                        }
                        return dataBufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        //WRITE_RESPONSE_FILTER 之前执行
        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
    }
}
